cmake_minimum_required(VERSION 3.10)
project(main C)

# --- 基本设置 ---
set(CMAKE_C_STANDARD 99)
set(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin)
include_directories(. ./program/include ./program/prac_inc) 
include_directories(./UI) # 包含 UI 目录以找到 ui.h)
include_directories(./freetype-2.13.3/include) # 包含 FreeType 头文件目录
include_directories(../lvgl/examples/libs/freetype) # 包含 FreeType 示例代码目录
link_directories(./freetype-2.13.3/build) # 包含 FreeType 库文件目录

# 启用LVGL示例
set(LV_BUILD_EXAMPLES ON)


# --- 平台检测与配置 ---
if(CMAKE_CROSSCOMPILING OR CMAKE_SYSTEM_PROCESSOR MATCHES "arm|aarch64" OR CMAKE_C_COMPILER MATCHES "arm-linux-")
    message(STATUS "目标架构: ARM (交叉编译)")
    set(TARGET_ARCH "arm")
    set(PLATFORM_LIBS pthread) # ARM平台链接pthread

# else()
#     message(STATUS "目标架构: PC (本地编译)")
#     set(TARGET_ARCH "pc")
#     find_package(SDL2 REQUIRED)
#     find_package(Threads REQUIRED)
#     # find_package(Freetype REQUIRED)  # 添加Freetype查找
#     # set(PLATFORM_LIBS ${PLATFORM_LIBS} ${FREETYPE_LIBRARIES})


#     set(PLATFORM_LIBS ${SDL2_LIBRARIES} Threads::Threads) # PC平台链接SDL2和pthreads
# endif()

else()
    message(STATUS "目标架构: PC (本地编译)")
    set(TARGET_ARCH "pc")
    
    # 查找 SDL2 并打印详细信息（关键调试）
    find_package(SDL2 REQUIRED)
    if(SDL2_FOUND)
        message(STATUS "SDL2 找到！头文件路径: ${SDL2_INCLUDE_DIRS}")
        message(STATUS "SDL2 库路径: ${SDL2_LIBRARIES}")  # 打印实际链接的库
    else()
        message(FATAL_ERROR "SDL2 未找到，请检查是否安装 libsdl2-dev")
    endif()
    
    find_package(Threads REQUIRED)
    
    # 明确设置平台库，确保 SDL2 被包含
    set(PLATFORM_LIBS ${SDL2_LIBRARIES} Threads::Threads)
endif()


# 运行脚本来修改 lv_drv_conf.h
execute_process(
    COMMAND bash ${CMAKE_CURRENT_SOURCE_DIR}/configure.sh ${TARGET_ARCH}
    WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
    RESULT_VARIABLE script_result
)
if(NOT script_result EQUAL 0)
    message(FATAL_ERROR "为 ${TARGET_ARCH} 配置 lv_drv_conf.h 失败")
endif()


# --- 添加子目录 ---
add_subdirectory(lvgl)
add_subdirectory(lv_drivers)
add_subdirectory(UI) # 添加 UI 子目录以构建 ui 库 (共享库)


# --- 构建主程序 ---
add_executable(${PROJECT_NAME} ./program/src/main.c ./program/src/mouse_cursor_icon.c ./program/prac/menu.c ./program/prac/ui_custom.c
                                lvgl/src/font/lv_font_montserrat_16.c) 

# 链接需要的库
target_link_libraries(${PROJECT_NAME} PRIVATE
    lvgl
    lvgl::drivers
    lvgl::demos      # 链接 LVGL 的 demos 库
    lvgl::examples   # 链接 LVGL 的 examples 库
    ${PLATFORM_LIBS} # 链接平台特定的库
    m                # 链接数学库
    ui               # 链接 UI 共享库
    freetype        # 链接 FreeType 库
)



# --- 为VSCode创建一个运行目标 ---
add_custom_target(run
    COMMAND ${EXECUTABLE_OUTPUT_PATH}/${PROJECT_NAME}
    DEPENDS ${PROJECT_NAME}
    WORKING_DIRECTORY ${PROJECT_BINARY_DIR}
)

message(STATUS "项目配置完成! 目标平台: ${TARGET_ARCH}")
